package com.renting.modules.timer;

import com.renting.modules.timer.entity.Timer;
import com.renting.modules.timer.sevice.TimerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开启timer定时器(关闭)
 */
//@Configuration
//@EnableScheduling
public class TimerSchedule implements SchedulingConfigurer {
    @Autowired
    private TimerService timerService;

    public static Map<String, CronTrigger> scheduleMap = new HashMap<>();


    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        List<Timer> timerList = timerService.getAll();
        timerList.forEach((timer) -> register(timer, scheduledTaskRegistrar));

    }

    private void register(Timer timer, ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                () -> System.out.println("执行定时任务" + timer.getDesc() + " : " + LocalDateTime.now().toLocalTime()),
                triggerContext -> {
                    String cron = timer.getCron();
                    CronTrigger cronTrigger = new CronTrigger(cron);
                    scheduleMap.put("timer_" + timer.getId(), cronTrigger);
                    /*todo 业务方法*/
                    return cronTrigger.nextExecutionTime(triggerContext);
                }
        );
    }


}
